package com.cheng.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheng.mapper.SummaryPlugMapper;
import com.cheng.mapper.TwoIndexMapper;
import com.cheng.mapper.TwoIndexPlugMapper;
import com.cheng.pojo.dto.EditGradeDto;
import com.cheng.pojo.dto.EditSummaryDto;
import com.cheng.pojo.dto.ListSummaryDto;
import com.cheng.pojo.dto.ListTwoIndexDto;
import com.cheng.pojo.po.Summary;
import com.cheng.pojo.po.TwoIndex;
import com.cheng.pojo.vo.Result;
import com.cheng.pojo.vo.RocketPeople;
import com.cheng.pojo.vo.RocketScoreStatus;
import com.cheng.pojo.vo.RocketStatus;
import com.cheng.service.ISummaryService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.cheng.redis.RedisConstants.*;


@Service
public class SummaryServiceImpl implements ISummaryService {
    @Resource
    private com.cheng.mapper.SummaryMapper summaryMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SummaryPlugMapper summaryPlugMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private TwoIndexMapper twoIndexMapper;
    @Resource
    private TwoIndexPlugMapper twoIndexPlugMapper;

    @Autowired
    public SummaryServiceImpl(TwoIndexMapper twoIndexMapper) {
        this.twoIndexMapper = twoIndexMapper;
    }

    @Override
    public Result listSummary(ListSummaryDto listSummaryDto) {

        // redis的大小键
        String redis_summary_big_key = SUMMARY_EDIT_KEY+String.valueOf(listSummaryDto.getYear());
        String redis_summary_small_key =
                (listSummaryDto.getUnit() == null ? null : listSummaryDto.getUnit()) +
                (listSummaryDto.getStatus() == null ? null : listSummaryDto.getStatus()) +
                (listSummaryDto.getScorestatus() == null ? null : listSummaryDto.getScorestatus());


        // 查询redis，判断是否为空
        String redisSummary = (String) stringRedisTemplate.opsForHash().get(redis_summary_big_key,redis_summary_small_key);
        if(redisSummary != null && !redisSummary.isEmpty()){
            return Result.ok(JSONUtil.toList(redisSummary, Summary.class));
        }
        System.out.println("redis未查询到数据，查询数据库");

        // 查询数据库
        List<Summary> summaryList = summaryMapper.listByFour(listSummaryDto.getYear(), listSummaryDto.getUnit(), listSummaryDto.getStatus(), listSummaryDto.getScorestatus());

        // 存入redis(设置过期时间)
        stringRedisTemplate.opsForHash().put(redis_summary_big_key,redis_summary_small_key, JSONUtil.toJsonStr(summaryList));
        stringRedisTemplate.expire(redis_summary_big_key, 60, TimeUnit.MINUTES);

        // 返回结果
        return Result.ok(summaryList);
    }


    @Override
    public Result editSummary(EditSummaryDto editSummaryDto) {
        int flag = editSummaryDto.getFlag();
        int statusFlag = editSummaryDto.getStatusFlag();
        String unit = editSummaryDto.getUnit();
        String comeName = editSummaryDto.getComeName();
        // 进展状态
        if(flag == -1){
            Result<Object> sendResult = getStatusResult(unit);
            if (sendResult != null){
                return sendResult;
            }
        }

        // 成绩身申述状态
        if(flag == -2){
            return getScoreStatusResult(statusFlag, unit);
        }

        // 审核人
        if(flag == -3){
            return getPeopleResult(unit, comeName);
        }

        return Result.ok("写错参数了吧");
    }

    @Override
    public Result listTwoIndex(ListTwoIndexDto listTwoIndexDto) {
        // 获取当前页数据
        if(listTwoIndexDto.getPageNo() <= 0){
            listTwoIndexDto.setPageNo(1);
        }
        int offset = (listTwoIndexDto.getPageNo() - 1) * listTwoIndexDto.getPageSize();
        int limit = listTwoIndexDto.getPageSize();

        // 定义变量获取redis中的数据
        String redis_twoIndex_get_page_big_key = TWOINDEX_GET_PAGE_KEY+listTwoIndexDto.getUnit();
        String redis_twoIndex_get_page_small_key =
                (listTwoIndexDto.getProgressstatus() == null ? null : listTwoIndexDto.getProgressstatus()) +
                (listTwoIndexDto.getAppealstatus() == null ? null : listTwoIndexDto.getAppealstatus()) +
                (listTwoIndexDto.getVagueIndex() == null ? null : listTwoIndexDto.getVagueIndex()) +
                (listTwoIndexDto.getVagueWork() == null ? null : listTwoIndexDto.getVagueWork()) +
                (offset) +
                (limit);

        String redis_twoIndex_get_page_total_big_key = TWOINDEX_GET_PAGE_TOTAL_KEY+listTwoIndexDto.getUnit();
        String redis_twoIndex_get_page_total_key =
                (listTwoIndexDto.getProgressstatus() == null ? null : listTwoIndexDto.getProgressstatus()) +
                (listTwoIndexDto.getAppealstatus() == null ? null : listTwoIndexDto.getAppealstatus()) +
                (listTwoIndexDto.getVagueIndex() == null ? null : listTwoIndexDto.getVagueIndex()) +
                (listTwoIndexDto.getVagueWork() == null ? null : listTwoIndexDto.getVagueWork());

        String redisTwoIndexPage = (String) stringRedisTemplate.opsForHash().get(redis_twoIndex_get_page_big_key,redis_twoIndex_get_page_small_key);
        String redisTwoIndexAll = (String) stringRedisTemplate.opsForHash().get(redis_twoIndex_get_page_total_big_key, redis_twoIndex_get_page_total_key);
        if(redisTwoIndexPage != null && !redisTwoIndexPage.isEmpty() && redisTwoIndexAll != null && !redisTwoIndexAll.isEmpty()){
            System.out.println("redis搜索到了" + redis_twoIndex_get_page_big_key + ":" + redis_twoIndex_get_page_small_key);
            return Result.ok(JSONUtil.toList(redisTwoIndexPage, TwoIndex.class), JSONUtil.toList(redisTwoIndexAll, TwoIndex.class));
        }
        System.out.println("进行数据库搜索" + redis_twoIndex_get_page_big_key + ":" + redis_twoIndex_get_page_small_key);

        // 查询数据库
        List<TwoIndex> summaryTwoIndices = twoIndexMapper.listTwoIndexByConditions(
                listTwoIndexDto.getUnit(),
                listTwoIndexDto.getProgressstatus(),
                listTwoIndexDto.getAppealstatus(),
                listTwoIndexDto.getVagueIndex(),
                listTwoIndexDto.getVagueWork(),
                offset,
                limit
        );
        List<TwoIndex> twoIndices = twoIndexMapper.listTwoIndexTotal(
                listTwoIndexDto.getUnit(),
                listTwoIndexDto.getProgressstatus(),
                listTwoIndexDto.getAppealstatus(),
                listTwoIndexDto.getVagueIndex(),
                listTwoIndexDto.getVagueWork(),
                offset,
                limit
        );

        // 存入redis(设置过期时间)
        stringRedisTemplate.opsForHash().put(redis_twoIndex_get_page_big_key,redis_twoIndex_get_page_small_key, JSONUtil.toJsonStr(summaryTwoIndices));
        stringRedisTemplate.expire(redis_twoIndex_get_page_big_key, 60, TimeUnit.MINUTES);
        stringRedisTemplate.opsForHash().put(redis_twoIndex_get_page_total_big_key,redis_twoIndex_get_page_total_key,JSONUtil.toJsonStr(twoIndices));
        stringRedisTemplate.expire(redis_twoIndex_get_page_total_big_key, 60, TimeUnit.MINUTES);

        return Result.ok(summaryTwoIndices, twoIndices.size());
    }

    @Override
    public Result addGrade(EditGradeDto editGradeDto) {
        twoIndexPlugMapper.updateById(new TwoIndex().builder().id(editGradeDto.getId()).indivscore(editGradeDto.getGrade()).build());
        return null;
    }

    // 获取当年年份
    private static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        return currentYear;
    }

    private Result<Object> getStatusResult(String unit) {
        // 搜索有的数据
        List<TwoIndex> twoIndices1 = twoIndexPlugMapper.selectList(
                new QueryWrapper<TwoIndex>()
                        .eq("year", getCurrentYear())
                        .eq("unit", unit)
                        .like("progressstatus", "待审核"));


        if(twoIndices1.size() != 0){
            SendResult sendResult = rocketMQTemplate.syncSend("summary:status", new RocketStatus().builder().year(getCurrentYear()).unit(unit).status("待审核").build());
            return Result.ok(sendResult);
        }

        List<TwoIndex> twoIndices2 = twoIndexPlugMapper.selectList(
                new QueryWrapper<TwoIndex>()
                        .eq("year", getCurrentYear())
                        .eq("unit", unit)
                        .like("progressstatus", "已保存"));
        if(twoIndices2.size() != 0){
            SendResult sendResult = rocketMQTemplate.syncSend("summary:status", new RocketStatus().builder().year(getCurrentYear()).unit(unit).status("已保存").build());
            return Result.ok(sendResult);
        }

        List<TwoIndex> twoIndices3 = twoIndexPlugMapper.selectList(
                new QueryWrapper<TwoIndex>()
                        .eq("year", getCurrentYear())
                        .eq("unit", unit)
                        .like("progressstatus", "已审核"));
        if(twoIndices3.size() != 0){
            SendResult sendResult = rocketMQTemplate.syncSend("summary:status", new RocketStatus().builder().year(getCurrentYear()).unit(unit).status("已审核").build());
            return Result.ok(sendResult);
        }
        return null;
    }

    private Result<Object> getScoreStatusResult(int statusFlag, String unit) {
        RocketScoreStatus rocketScoreStatus = new RocketScoreStatus();

        if (statusFlag == 2) {
            rocketScoreStatus = new RocketScoreStatus().builder().year(getCurrentYear()).unit(unit).scorestatus("待审核").build();
        }
        if (statusFlag == 3) {
            rocketScoreStatus = new RocketScoreStatus().builder().year(getCurrentYear()).unit(unit).scorestatus("已审核").build();
        }
        SendResult sendResult = rocketMQTemplate.syncSend("summary:scorestatus", rocketScoreStatus);
        return Result.ok(sendResult);
    }


    private Result<Object> getPeopleResult(String unit, String comeName) {
        RocketPeople rocketPeople = new RocketPeople().builder().year(getCurrentYear()).unit(unit).people(comeName).build();
        rocketMQTemplate.asyncSend("summary:people", rocketPeople, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("生产者:  异步发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("生产者:  异步发送失败");
            }
        });
        return Result.ok("修改成功-33");
    }


}
